<?php
namespace app\admin\controller;

use app\admin\model\Admin as AdminModel;
use app\admin\model\Role;
use think\Request;
use think\Config;
use think\Cache;
use think\Validate;

class Admin extends Base
{

	/**
     * 获取当前访问路由
     * @param $Request
     * @return string
     */
    public function get_action_url()
    {
        $module     = request()->module();
        $controller = request()->controller();
        $action     = request()->action();
        $url        = $module.'/'.$controller.'/'.$action;
        return strtolower($url);
    }

	/**
	*	管理员列表
    */
	public function index()
	{
		$map = [];
        if (!empty($this->request->param('keywords'))) {
            $key = $this->request->param('keywords');
            $map['a.username|a.nick'] = array('like', "%{$key}%");
        }
        if (!empty($this->request->param('status'))) {
            $map['a.status'] = $this->request->param('status');
        }
        if (!empty($this->request->param('role_id'))) {
            $map['a.role_id'] = $this->request->param('role_id');
        }

		$list = AdminModel::alias('a')
			->join('d_roles r', 'a.role_id = r.id', 'LEFT')
			->where($map)
			->order('a.role_id ASC, a.create_at DESC')
			->field('a.id, a.username, a.nick, a.create_at, a.end_time, a.status, r.role_name')
			->paginate(10);

		$role_list = Role::field('id, role_name')->select();
		// $list = [];
// dd($list);
		$menu = self::getMenuArr();

		return view('index', compact('list', 'role_list', 'menu'));
	}

	/**
	*	添加管理员
    */
    public function add()
    {
    	if(Request::instance()->isPost()){
    		$data = $this->request->param();
    		// dd($data);
	        $validate = new Validate([
	            ['username', 'require|unique:admins|max:11|/^1[3-9]{1}[0-9]{9}$/', '请输入登录账号|该账号已存在|账号长度有误|手机号码格式不正确'],
	            ['password', 'require|length:6,18', '请输入密码|密码长度6~18个字符'],
	            ['nick', 'require', '请输入真实姓名'],
	            ['status', 'require', '请选择登录状态'],
	            ['role_id', 'require', '请选择角色'],
	        ]);
	        if (!$validate->check($data)) {
	            return error($validate->getError());
	        }

	        $res = AdminModel::create([
	        	'username' => $data['username'],
	        	'password' => md5(sha1($data['password'])),
	        	'nick' => $data['nick'],
	        	'status' => $data['status'],
	        	'portrait' => $data['portrait'],
	        	'role_id' => $data['role_id'],
	        	'create_at' => time()
	        ]);

	        if(!$res){
	        	return error('添加失败');
	        }
	        logger(2, '添加管理员账户：'.$data['username']);

	        return success(['url'=>"/admin/admin/index"], '添加成功');


    	}

    	$role_list = Role::where('status', 1)->field('id, role_name')->select();
    	// dump(md5(sha1('123456')));exit;
    	$menu = self::getMenuArr();

    	return view('add', compact('role_list', 'menu'));
    }

    /**
	*	编辑管理员
    */
    public function edit()
    {
    	$id = $this->request->param('id');
    	$detail = AdminModel::field('id, username, nick, status, portrait, role_id')->find($id);
    	$role_list = Role::field('id, role_name')->select();

    	if(Request::instance()->isPost()){
    		$data = $this->request->param();
    		// dd($data);
	        $validate = new Validate([
	            ['nick', 'require', '请输入真实姓名'],
	            ['status', 'require', '请选择登录状态'],
	            ['role_id', 'require', '请选择角色'],
	        ]);
	        if (!$validate->check($data)) {
	            return error($validate->getError());
	        }

	        //判断是否修改密码
	        if(!empty($data['password'])){
	        	$detail->password = md5(sha1($data['password']));
	        }
	        //判断是否修改头像
	        if($detail['portrait'] != $data['portrait']){
	        	//先删除旧头像
	        	@unlink(ROOT_PATH . 'public' . DS . 'uploads' . DS . $detail['portrait']);

	        	//重新赋值头像的路径
	        	$detail->portrait = $data['portrait'];
	        }

	        $detail->nick = $data['nick'];
	        $detail->status = $data['status'];
	        $detail->role_id = $data['role_id'];
	        $res = $detail->save();

	        if($res || $res !== false){
	        	logger(2, '编辑管理员账户：'.$data['nick']);
	        	return success(['url'=>"/admin/admin/index"], '更新成功');
	        }
	        
	        return error('更新失败');

    	}
    	$menu = self::getMenuArr();

    	return view('edit', compact('detail', 'role_list', 'menu'));
    }


    /**
	*	修改个人信息
    */
    public function modify_info()
    {
    	if(Request::instance()->isPost()){
    		$data = $this->request->param();
	        $validate = new Validate([
	        	['username', 'require|max:11|/^1[3-9]{1}[0-9]{9}$/', '请输入手机号码|手机号码最多不能超过11个字符|手机号码格式不正确'],
	            ['nick', 'require|length:2,10', '请输入真实姓名|昵称2～10个中文汉字'],
	        ]);
	        if (!$validate->check($data)) {
	            return error($validate->getError());
	        }

	        $res = AdminModel::where('id', $this->user->id)->update($data);

	        if($res || $res !== false){
	        	logger(2, '修改个人信息');

	            return success(1, '信息修改成功');
	        }

	        return error('资料修改失败');

    	}	

    	$user = $this->user;
    	$menu = self::getMenuArr();
       

    	return view('modify_info', compact('user', 'menu'));
    }

    /**
	*	修改登录密码
    */
    public function modify_pass()
    {
    	if(Request::instance()->isPost()){
    		$data = $this->request->param();
	        $validate = new Validate([
	            	['old_password', 'require', '请输入原密码'],
	            	['password', 'require|length:6,18', '请输入新密码|密码长度6~18个字符'],
            		['repassword', 'require|confirm:password', '请输入确认新密码|两次密码不一致'],
	        ]);
	        if (!$validate->check($data)) {
	            return error($validate->getError());
	        }

	        $pass =AdminModel::where('id', $this->user->id)->value('password');
	        $old_password = md5(sha1($data['old_password']));
	        if($old_password != $pass){
	        	return error('原密码不正确');
	        }

	        $res = AdminModel::where('id', $this->user->id)->update(['password' => md5(sha1($data['repassword']))]);

	        if(!$res){
	        	return error('修改失败');
	        }
	        logger(2, '修改个人登录密码');

	        session('admin_info', null);

        	return success(['url'=>'/admin/login/index'], '修改成功，请重新登录');

    	}
    	$menu = self::getMenuArr();

    	return view('modify_pass', compact('menu'));
    }

    /**
	*	删除管理员
    */
	public function admin_del($id)
	{
		if(empty($id) || $id == ''){
			return error('参数有误');
		}

		$res = AdminModel::get($id);
		if(!$res){
			return error('数据不存在或已被删除');
		}
		logger(2, '删除管理员账户：'.$res['username']);
        $res->delete();

		return success(1, '删除成功！');

	}
}
